package cn.time1024.time_app.ui.account

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.timeassistant.network.ApiService
import cn.time1024.time_app.R

class TransactionsAdapter(
    private val onEdit: (ApiService.TransactionItem) -> Unit,
    private val onDelete: (ApiService.TransactionItem) -> Unit
) : RecyclerView.Adapter<TransactionsAdapter.VH>() {

    private val items = mutableListOf<ApiService.TransactionItem>()

    class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvTitle: TextView = itemView.findViewById(R.id.tvTitle)
        val tvSub: TextView = itemView.findViewById(R.id.tvSub)
        val btnEdit: View = itemView.findViewById(R.id.btnEdit)
        val btnDelete: View = itemView.findViewById(R.id.btnDelete)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_transaction, parent, false)
        return VH(v)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: VH, position: Int) {
        val item = items[position]
        val amount = item.amount ?: 0.0
        val type = item.type ?: "支出"
        val cat = item.category ?: "未分类"
        val date = item.transactionDate ?: ""
        holder.tvTitle.text = "${if (type == "收入") "+" else "-"}${String.format("%.2f", amount)} · ${cat}"
        holder.tvSub.text = date + (if (!item.note.isNullOrBlank()) " · ${item.note}" else "")
        holder.btnEdit.setOnClickListener { onEdit(item) }
        holder.btnDelete.setOnClickListener { onDelete(item) }
    }

    fun replaceAll(list: List<ApiService.TransactionItem>) {
        items.clear()
        items.addAll(list)
        notifyDataSetChanged()
    }

    fun appendAll(list: List<ApiService.TransactionItem>) {
        val start = items.size
        items.addAll(list)
        notifyItemRangeInserted(start, list.size)
    }
}
